//
//  LeetCodes.swift
//  DataStructureAndAlgorithm
//
//  Created by icemelon on 2021/8/4.
//

extension Stack {
    //20. 有效的括号
    static func isValid(_ s: String) -> Bool {
        if s.count % 2 == 1 {
                    return false
                }
        let bracketDict: [Character: Character] = ["(": ")", "[": "]", "{": "}"]
        var stack = Stack<Character>()
        for c in s {
            if bracketDict.keys.contains(c) {
                stack.push(element: c)
            }
            else {
                if let leftChar = stack.pop() {
                    if c == bracketDict[leftChar] {
                        continue
                    }
                    else {
                        return false
                    }
                }
                else {
                    return false
                }
            }
        }
        
        
        return stack.isEmpty()
    }
    
    static func isValid2(_ s: String) -> Bool {
        var str = s
        while str.contains("()") || str.contains("[]") || str.contains("{}") {
            str = str.replacingOccurrences(of: "()", with: "")
            str = str.replacingOccurrences(of: "[]", with: "")
            str = str.replacingOccurrences(of: "{}", with: "")
        }
        
        
        return str.isEmpty
    }
    
    func isLeftBracket(c: Character) -> Bool {
        return Character.bracketDict.keys.contains(c)
    }
}
